package com.cmii.sjw.department.control.jsc.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cmii.sjw.department.control.enums.AnswerSourceTypeEnum;
import com.cmii.sjw.department.control.jsc.config.YcConfig;
import com.cmii.sjw.department.control.jsc.constant.Constants;
import com.cmii.sjw.department.control.jsc.mapper.AiConfigMapper;
import com.cmii.sjw.department.control.jsc.model.AiConfig;
import com.cmii.sjw.department.control.jsc.model.YcDetail;
import com.cmii.sjw.department.control.jsc.model.params.CqxczwyAiConfigParams;
import com.cmii.sjw.department.control.jsc.service.AiService;
import com.cmii.sjw.department.control.jsc.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;

/**
 * @Author jfh
 * @Date 2025-02-10 周一 10:21
 * @Version 1.0
 */
@Slf4j
@Service
public class AiServiceImpl implements AiService {

    @Autowired
    private YcConfig ycConfig;

    @Autowired
    private AiConfigMapper aiConfigMapper;

    /**
     * 获取云从AI的token
     * @return
     *
     */
    @Override
    public Result getYcAiToken() {

        String authorization = "Basic " + Base64.encode(ycConfig.getAccessKey() + ":" + ycConfig.getSecretKey());
        HttpResponse httpResponse = HttpRequest.post(ycConfig.getUrl()+"/sso/oauth/token")
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .header("Authorization", authorization)
                .form("grant_type", "password")
                .form("username", ycConfig.getUsername())
                .form("password", ycConfig.getPassword()).execute();
        String body = httpResponse.body();
        log.info("token result:{}", body);
        String accessToken = null;
        if (httpResponse.isOk()) {
            JSONObject bodyObj = JSONObject.parseObject(body);
            accessToken = bodyObj.getString("access_token");
        } else {
            log.error("get token failed, status:" + httpResponse.getStatus());
            return Result.error("get token failed, status" ,httpResponse.getStatus());
        }

        return Result.success(accessToken);
    }

    /**
     * 获取知识库详情
     * @param token 云从AI token
     * @param id 问答记录ID，id为智能体文本对话中的recordId
     * @return
     */
    @Override
    public Result detail(String token, String id) {
        try {
            URI uri = URI.create(ycConfig.getUrl()).resolve("/llm_copilot/record/detail");
            JSONObject jsonObject = new JSONObject().fluentPut("id", id);

            HttpResponse httpResponse = HttpRequest.post(uri.toString())
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.AUTHORIZATION, Constants.BEARER + " " + token.trim())
                    .body(jsonObject.toJSONString())
                    .execute();

            int statusCode = httpResponse.getStatus();
            if (statusCode < 200 || statusCode >= 300) {
                log.error("HTTP请求失败. Status: {}, URL: {}", statusCode, uri);
                return Result.error("请求失败 status: " + statusCode);
            }

            String body = httpResponse.body();
            log.debug("Detail response: {}", body);  // 改用debug级别

            com.alibaba.fastjson2.JSONObject content = com.alibaba.fastjson2.JSON.parseObject(body);
            if (content == null || !content.getBooleanValue("success")) {
                log.warn("响应内容无效. Status: {}, Body: {}", statusCode, body);
                return Result.error("响应格式无效");
            }

            YcDetail resultData = content.getObject("data", YcDetail.class);
            if (resultData == null) {
                log.warn("响应中为空数据. Body: {}", body);
                return Result.error("未找到详细数据");
            }

            return Result.success(AnswerSourceTypeEnum.valueOf(resultData.getAnswerSourceType() == null ? 0 : resultData.getAnswerSourceType()).getDescription());
        } catch (Exception e) {
            log.error("详细信息请求失败. ID: {}, Error: {}", id, e.getMessage(), e);
            return Result.error("服务不可用");
        }
    }

    /**
     * 获取AI底座配置信息
     * @param params 参数
     * @return 结果
     */
    @Override
    public Result<AiConfig> cqxczwyAiConfig(CqxczwyAiConfigParams params) {
        AiConfig aiConfig = aiConfigMapper.selectOne(new LambdaQueryWrapper<AiConfig>()
                .eq(AiConfig::getName, params.getName())
                .eq(AiConfig::getStatus, params.getStatus()));

        if (aiConfig == null) {
            return Result.error("未找到该AI底座配置信息");
        }
        return Result.success(aiConfig);
    }


}
